package ru.aslanov.schedule.utils;

import java.io.PrintWriter;

/**
 * Created by IntelliJ IDEA.
 * Created: Mar 2, 2010 11:17:40 AM
 *
 * @author Sergey Aslanov
 */
public class JSUtil {

    public static void printResponse(PrintWriter writer, String callbackName, boolean closeWindow, boolean isChildWindow, Param... params) {
        writer.println("<html><body><script type='text/javascript'>");
        writer.println("var res = new Object();");
        for (Param param : params) {
            writer.println("res." + param.name + " = " + toJSValue(param.value) + ";");
        }
        String parentWin;
        if (isChildWindow) parentWin = "window.opener.";
        else parentWin = "window.top.";
        
        writer.println(parentWin + callbackName + "(res);");
        if (isChildWindow && closeWindow) {
            writer.println("window.close();");            
        }
        writer.println("</script></body></html>");
    }

    private static String toJSValue(Object value) {
        String res;
        if (value == null) {
            res = "null";
        } else if (value instanceof String) {
            res = "'" + ((String) value).replaceAll("\n", " ").replaceAll("'","\"")+ "'";            
        } else {
            res = value.toString();
        }
        return res;
    }


    public static final class Param {
        private String name;
        private Object value;

        public Param(String name, Object value) {
            this.name = name;
            this.value = value;
        }
    }

}
